package com.example.doublewrite.service;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.doublewrite.mapper.OrderItemMapper;
import com.example.doublewrite.mapper.OrderItemMapper2;
import com.example.doublewrite.mapper.OrderMapper;
import com.example.doublewrite.mapper.OrderMapper2;
import com.example.doublewrite.model.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserOrderService {


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper itemMapper;

    @Autowired
    private OrderMapper2 orderMapper2;

    @Autowired
    private OrderItemMapper2 itemMapper2;


    @Transactional
    public void createOrder() {
        for (long i = 0; i < 12; i++) {
/*            if (i == 6L) {
                int k = 3 / 0;
            }*/
            Order order = new Order(null, i + 10000, i + 20001, new BigDecimal(0), 1);

            orderMapper.insert(order);
            Order2 order2 = new Order2();
            BeanUtils.copyProperties(order, order2);
            orderMapper2.insert(order2);

            for (long j = 0; j < 3; j++) {
                OrderItem orderItem = new OrderItem(null, order.getOrderId(), order.getUserId(), order.getMerchantId(), new BigDecimal(2));

                itemMapper.insert(orderItem);
                OrderItem2 orderItem2 = new OrderItem2();
                BeanUtils.copyProperties(orderItem, orderItem2);
                itemMapper2.insert(orderItem2);

                order.setAmount(order.getAmount().add(orderItem.getAmount()));
            }
            LambdaUpdateWrapper<Order> updateWrapper = Wrappers.lambdaUpdate(Order.class)
                    .eq(Order::getOrderId, order.getOrderId()).eq(Order::getUserId, order.getUserId())
                    .set(Order::getAmount, order.getAmount());

            orderMapper.update(new Order(), updateWrapper);
            LambdaUpdateWrapper<Order2> updateWrapper2 = Wrappers.lambdaUpdate(Order2.class)
                    .eq(Order2::getOrderId, order.getOrderId()).eq(Order2::getMerchantId, order.getMerchantId())
                    .set(Order2::getAmount, order.getAmount());
            orderMapper2.update(new Order2(), updateWrapper2);

        }


    }

    public List<OrderDTO> getOrderListByUserId(Long userId) {
        return orderMapper.getOrderListByUserId(userId);
    }

}
